<?php
namespace shopend\controllers;


use common\models\Active;
use common\models\ActiveAttr;
use common\models\Goods;
use common\models\GoodsAttr;
use common\models\AttributeValue;
use common\models\Order;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\GoodsService;
use common\service\WechatService;
use common\service\RedisServer;
use common\service\ActiveService;

class ActiveController extends BaseController
{
    /**
     * 活动列表页
     * @return string
     */
    public function actionIndex(){
        if($this->isAjax() && $this->isGet()){
            $query = Active::find();
            $query->andWhere(['is_del'=>0]);
            $query->andWhere(['shop_id'=>$this->shop['id']]);
            if(!empty($this->get('active_name'))){
                $query->andWhere(['like','active_name',$this->get('active_name')]);
            }
            if(!empty($this->get('type'))){
                $query->andWhere(['type'=>$this->get('type')]);
            }
            $p = intval( $this->get('page',1) );
            $p = ( $p > 0 )? $p : 1;
            $count = $query->count();

            $offset = ($p - 1) * $this->get('limit',10);

            $lists = $query->orderBy(['set_top' => SORT_DESC,'update_time' => SORT_DESC])
                ->offset( $offset )
                ->limit( $this->get('limit',10) )
                ->asArray()
                ->all();
            return $this->renderPageJson($lists,$count,ConstantService::$response_tab_success);
        }
        $type = $this->get('type');
        return $this->render('index',['type'=>$type]);
    }

    /**
     * 添加活动
     */
    public function actionAdd(){
        if($this->isPost() && $this->isAjax()){

            $data = $this->post();
            $attrs = $data['active_attr'];

            $msg = $this->_validate($data);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            //检查商品库存
            $modify_inventory = $this->_GetGoodsAttr($attrs);

            $goodsData = Goods::find()
                ->select('list_img')
                ->where(['id'=>$data['goods_id']])
                ->asArray()
                ->one();

            unset($data['active_attr']);
            $collage_price = array_column($attrs,'collage_price');
            $data['shop_id'] = $this->shop['id'];
            $data['status'] = 0;
            $data['begin_time'] = strtotime($data['begin_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['qrcode'] = '';
            $data['is_del'] = 0;
            $data['sales_volume'] = 0;
            $data['display_sales'] = 0;
            $data['type'] = 0;
            $data['set_top'] = 0;
            $data['max_price'] = max($collage_price);
            $data['min_price'] = min($collage_price);
            $data['goods_img'] = $goodsData['list_img'];
            $data['create_time'] = time();
            $data['update_time'] = time();
            $active_model = new Active();
            $active_model->setAttributes($data);
            if($active_model->save()){
                $active_id = \Yii::$app->db->getLastInsertID();
                foreach ($attrs as &$attr){
                    $attr['active_id'] = $active_id;
                    $attr['sales_volume'] = 0;
                    $attr['is_del'] = 0;
                    $attr['create_time'] = time();
                    $attr['update_time'] = time();
                }

                //保存属性值
                $re = ActiveAttr::getDb()->createCommand()->batchInsert('active_attr',
                    ['attr_img','collage_price','original_price','inventory','attribute_value_id','goods_attre_id','active_id','sales_volume','is_del','create_time','update_time'],
                    $attrs)->execute();
                if($re){
                    //减商品库存
                    $this->_modifyInventory($modify_inventory);
                    return $this->renderJson([],'活动添加成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'保存活动属性失败',ConstantService::$response_fail);
            }
            return $this->renderJson([],'保存主要活动信息失败',ConstantService::$response_fail);
        }

        $shop_id=$this->shop['id'];
        //得到商家在活动中和被删除的活动
        $activity_data_id = Active::find()
            ->orWhere(['status'=>1])
            ->orWhere(['is_del'=>1])
            ->select('goods_id')
            ->asArray()
            ->all();
        $goods_id_ac = array_column($activity_data_id,"goods_id");
        $goods_data_id = Goods::find()
            ->where(['shop_id'=>$shop_id])
            ->where(['is_del'=>0])
            ->asArray()
            ->all();
        //取商家未进行中活动的id
        $goods_id_gd = array_column($goods_data_id,'id');
        $goods_id = array_diff($goods_id_gd,$goods_id_ac);
        $active_type = ConstantService::$active_type;
        //查出还可以参加活动的商品
        $goods_data = Goods::find()
            ->andWhere(['in','id',$goods_id])
            ->asArray()
            ->all();
        return $this->render('add',[
            'datas'=>$goods_data,
            'cdn'=>GlobalUrlService::buildCdnUrl(''),
            'active_type' => $active_type,
        ]);
    }



    /**
     * 修改活动属性
     * @return string|void
     */
    public function actionUpdate(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $msg = $this->_validate($data);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $active = Active::find()->where(['id'=>$data['id']])->one();
            $active_attr = $this->post("active_attr");

            //修改活动检索库存
            $goods_attr_data = GoodsAttr::find()->select(['id','inventory'])->where(['goods_id'=>$active['goods_id']])->asArray()->all();
            $active_attr_data = ActiveAttr::find()->select(['id','goods_attre_id','inventory'])->where(['active_id'=>$data['id']])->asArray()->all();
            foreach ($goods_attr_data as $aad){
                $Newgoods_attr_data[$aad['id']] = $aad;
            }
            foreach ($active_attr_data as $aad){
                $Newactive_attr_data[$aad['goods_attre_id']] = $aad;
            }
            $invent = [];//商品库存
            foreach ($active_attr as $v){
                $inum = $Newgoods_attr_data[$v['goods_attr_id']]['inventory'];
                if(isset($Newactive_attr_data[$v['goods_attr_id']])){
                    $inum += $Newactive_attr_data[$v['goods_attr_id']]['inventory'];
                    unset($Newactive_attr_data[$v['goods_attr_id']]);
                }
                if (trim($inum) <  trim($v['inventory'])){
                    return $this->renderJson([],'活动库存大于商品库存，请修改商品库存',ConstantService::$response_fail);
                } else {
                    $inventdata['inventory'] = $inum-$v['inventory'];
                    $inventdata['id'] = $v['goods_attr_id'];
                    $invent[] = $inventdata;
                }
            }


            $delattrid = []; //删除过的活动库存
            foreach ($Newactive_attr_data as $ins){
                $inventdata['inventory'] = $Newgoods_attr_data[$ins['goods_attre_id']]['inventory']+$ins['inventory'];
                $inventdata['id'] = $ins['goods_attre_id'];
                $invent[] = $inventdata;
                $delattrid[] = $ins['id'];
            }
            $collage_price = array_column($active_attr,'collage_price');
            $data['status'] = 0;
            if(strtotime($data['end_time']) < time()){
                $data['status'] = 2;
            }
            $active->setAttributes([
                'active_name'=> $data['active_name'] ,
                'active_num'=>$data['active_num'] ,
                'max_price' => max($collage_price),
                'min_price' => min($collage_price),
                'begin_time' => strtotime($data['begin_time']),
                'end_time' => strtotime($data['end_time']),
                'status' => $data['status'] ,
            ]);

            $save = $active->save();
            if ($save){
                // 查询数据库中原有的活动属性
                $addattr = [];
                foreach($active_attr as $value){
                    $active_attr_model = ActiveAttr::find()->where(['active_id'=>$data['id'],'goods_attre_id'=>$value['goods_attr_id']])->one();
                    //判断活动是否添加过该属性有就直接改 没有就新增
                    if($active_attr_model){
                        $active_attr_model->attr_img = $value['attr_img'];
                        $active_attr_model->original_price = $value['original_price'];
                        $active_attr_model->collage_price = $value['collage_price'];
                        $active_attr_model->inventory = $value['inventory'];
                        $active_attr_model->is_del = 0;
                        $active_attr_model->update_time = time();
                        $active_attr_model->save(false);
                    } else {
                        $attr['attr_img'] = $value['attr_img'];
                        $attr['collage_price'] = $value['collage_price'];
                        $attr['original_price'] = $value['original_price'];
                        $attr['inventory'] = $value['inventory'];
                        $attr['attribute_value_id'] = $value['activity_attr_id'];
                        $attr['goods_attre_id'] = $value['goods_attr_id'];
                        $attr['active_id'] = $data['id'];
                        $attr['sales_volume'] = 0;
                        $attr['is_del'] = 0;
                        $attr['create_time'] = time();
                        $attr['update_time'] = time();
                        $addattr[] = $attr;
                    }
                }

                //添加活动属性
                if(!empty($addattr)) {
                    ActiveAttr::getDb()->createCommand()->batchInsert('active_attr',
                        ['attr_img', 'collage_price', 'original_price', 'inventory', 'attribute_value_id', 'goods_attre_id', 'active_id', 'sales_volume', 'is_del', 'create_time', 'update_time'],
                        $addattr)->execute();
                }
                //删除未选择的活动属性
                ActiveAttr::updateAll(['is_del'=>1,'inventory'=>0,'update_time'=>time()],['id'=>$delattrid]);
                $this->_modifyInventory($invent);
                return  $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return  $this->renderJson([],'修改失败',ConstantService::$response_fail);

        }
        $activity_id = $this->get('id');
        $activity = Active::findOne(['id'=>$activity_id]);
        $activity_attr = $this->GetAttrlist($activity_id);
        $cdn = GlobalUrlService::buildCdnUrl('');
        $active_type = ConstantService::$active_type;
        return  $this->render('update',[
            'activity'=>$activity,
            'activity_attr'=>$activity_attr,
            'activity_id'=>$activity_id,
            'goods_id'=>$activity['goods_id'],
            'active_type'=>$active_type,
            'cdn' => $cdn
        ]);

    }

    //查询活动详情
    public function actionActiveInfo(){
        $aid = $this->get('id');
        $active = Active::find()->where(['id'=>$aid])->asArray()->one();

        $activeAttr = $this->GetAttrlist($aid);
        $active_type = ConstantService::$active_type;
        return  $this->render('active-info',[
            'active_attr' => $activeAttr,
            'active' => $active,
            'active_type' => $active_type
        ]);
    }
    /**
     * 活动属性值
     * @param $id
     * @param int $type
     * @return mixed
     */
    public function GetAttrlist($id){
        $lists = ActiveAttr::find();
        $lists->andWhere(['active_id'=>$id,'is_del'=>0]);

        $list = $lists->asArray()->all();
        $aid = explode('-',$list[0]['attribute_value_id']);

        $attrtitle = AttributeValue::find()->where(['id'=>$aid])->orderBy(['id'=>SORT_ASC])->asArray()->all();
        $vid = array_column($list,'attribute_value_id');

        $newdata['thead'] = array_column($attrtitle,'attr_name');
        $newiddata = [];
        foreach ($vid as $val){
            $newid = explode('-',$val);
            foreach ($newid as $vid){
                if($vid > 0) {
                    $newiddata[] = $vid;
                }
            }
        }
        $newiddata = array_unique($newiddata);
        $newvaldata = AttributeValue::find()->where(['in','id',$newiddata])->asArray()->all();
        $valdatanew = array();
        foreach ($newvaldata as $newdats){
            $valdatanew[$newdats['id']] = $newdats;
        }

        $data = [];
        foreach ($list as $lval){
            $newavid = explode('-',$lval['attribute_value_id']);
            $newvalue['original_price'] = $lval['original_price'];
            $newvalue['collage_price'] = $lval['collage_price'];
            $newvalue['inventory'] = $lval['inventory'];
            $newvalue['image'] = GlobalUrlService::buildCdnUrl($lval['attr_img']);
            $newvalue['attr_img'] = $lval['attr_img'];
            $newvalue['attribute_value_id'] = $lval['attribute_value_id'];
            $newvalue['active_id'] = $lval['active_id'];
            $newvalue['goods_attre_id'] = $lval['goods_attre_id'];
            $newvalue['id'] = $lval['id'];
            $namedata = array();
            $attrvaldata = array();
            foreach ($newavid as $newval){
                if($newval > 0) {
                    $namedata[] = $valdatanew[$newval];
                    $attrvaldata[] = $valdatanew[$newval]['value'];
                }
            }
            $newvalue['attr_value'] = implode(':',$attrvaldata);
            $newvalue['val'] = $namedata;
            $newvalue['sales_volume'] = $lval['sales_volume'];
            $data[] = $newvalue;
        }
        $newdata['tbody'] = $data;
        return $newdata;
    }
    /**
     * 商品搜索
     */
    public function actionSearchGoods(){
        if($this->isAjax()) {
            $goods_name = $this->get('goods_name');
            $query = Goods::find();
            $query->andWhere(['is_del' => 0]);
            $query->andWhere(['shop_id' => $this->shop['id']]);
            if (!empty($goods_name)) {
                $query->andWhere(['like', 'goods_name', $goods_name]);
            }

            $p = intval($this->get('p', 1));
            $p = ($p > 0) ? $p : 1;
            $offset = ($p - 1) * $this->get('limit',10);
            $lists = $query
                ->select(['id', 'goods_name'])
                ->orderBy(['created_at' => SORT_DESC, 'id' => SORT_ASC])
                ->offset($offset)
                ->limit($this->get('limit',10))
                ->asArray()
                ->all();
            $data['lists'] = $lists;
            $pages = CommonService::ipagination([
                'total_count' => $query->count(),//总条数
                'page_size' => $this->get('limit',10),
                'page' => $p,
                'display' => 10
            ]);
            $data['count'] = $pages;
            return $this->renderJson($data, '获取成功', ConstantService::$response_success);
        }
        return $this->renderJson([], '参数错误！', ConstantService::$response_fail);
    }

    /**
     * 获取商品SKU
     */
    public function actionGetsku(){
        $goods_id = $this->post('id');
        $aid = $this->post('aid');
        $skuData = GoodsService::GetAttrlist($goods_id,0,$aid);
        $cdn = GlobalUrlService::buildCdnUrl('');
        if ($skuData){
            return $this->renderJson(['goods_attr'=>$skuData,'cdn'=>$cdn],"获取成功",ConstantService::$response_success);
        }
        return $this->renderJson([],'获取失败',ConstantService::$response_fail);
    }

    /**
     * 活动状态修改
     */
    public function actionSetStatus(){
        $id = $this->post('id');
        $type = $this->post('type');
        $data = Active::findOne(['id'=>$id]);
        $time = time();
        if($type == 1) {
            if ($data['begin_time'] > $time) {
                return $this->renderJson([], '活动未开始不能激活!', ConstantService::$response_fail);
            }
            if ($data['end_time'] < $time) {
                return $this->renderJson([], '活动已结束不能激活!', ConstantService::$response_fail);
            }
        }
        $data['status'] = $type;
        $re = $data->save();
        if ($re){
            return $this->renderJson([],'操作成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'操作失败',ConstantService::$response_fail);
    }

    // 删除活动
    public function actionDel(){
        $id = $this->post('id');
        $data = Active::findOne(['id'=>$id]);
        $data->is_del = 1;
        $re = $data->save();
        if ($re){
            ActiveService::DelActive($id);
            return $this->renderJson([],'删除成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'删除失败',ConstantService::$response_fail);
    }

    //活动二维码
    public function actionQrcode(){
        $aid = $this->post('id');
        $active = Active::find()->where(['id'=>$aid])->one();
        if (empty($active['qrcode'])){
            $qrcode = WechatService::getWechatQrcode($aid,"pages/detail/detail");
            if($qrcode===false){
                return $this->renderJson([],'获取失败',ConstantService::$response_fail);
            }
            $active["qrcode"] = $qrcode;
            $active->save();
            $cdnUrl = GlobalUrlService::buildCdnUrl($qrcode);
            return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
        }
        $path = $active["qrcode"];
        $cdnUrl = GlobalUrlService::buildCdnUrl("$path");
        return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
    }
    /**
     * 验证数据
     * @param $data
     * @return bool|string
     */
    private function _validate($data){

        if(empty($data['goods_id'])){
            return '商品id不能为空';
        }

        if(empty($data['active_name'])){
            return '活动名称不能为空';
        } else {
            $active = Active::find();
            $active->andWhere(['active_name'=>$data['active_name']]);
            $active->andWhere(['is_del'=>0]);
            $active->andWhere(['shop_id'=>$this->shop['id']]);
            if(isset($data['id'])){
                $active->andWhere(['!=','id',$data['id']]);
            }
            $activeData = $active->asArray()->one();

            if(!empty($activeData)){
                return "活动名称已存在";
            }
        }
        if(empty($data['active_num'])){
            return '参团人数不能为空';
        }
        if(empty($data['begin_time'])){
            return '开团时间不能为空';
        }

        if(empty($data['end_time'])){
            return '结束时间不能为空';
        }
        if(empty($data['active_attr'])){
            return '活动属性不能为空';
        }
        $begin_time = strtotime($data['begin_time'].'00:00:00');
        $end_time = strtotime($data['end_time'].'23:59:59');
        if($begin_time>$end_time){
            return '开团时间不允许大于结束时间';
        }
        if($data['active_num'] > 10){
            return '参团人数最多10人';
        }
        if(empty($data['active_attr'])){
            return '活动属性不允许为空';
        }

        return true;
    }
    /**
     * 添加检查商品库存
     */
    private function _GetGoodsAttr($attrs){
        $goods_attre_ids = array_column($attrs,'goods_attre_id');

        $goods_attrs = GoodsAttr::find()->where(['id'=>$goods_attre_ids])->asArray()->all();
        $new_goods_attr = [];
        foreach ($goods_attrs as $val){
            $new_goods_attr[$val['id']] = $val;
        }
        $modify_inventory = []; //需要修改的库存和id
        $errors = '';
        //判断库存
        foreach ($attrs as $attr){
            if($attr['inventory'] < 1){
                $errors .= '拼团价为'.$attr['collage_price'] .'的商品库存不能为0!';
                continue;
            }
            if(isset($new_goods_attr[$attr['goods_attre_id']] ) && !empty($new_goods_attr[$attr['goods_attre_id']])){
                if($new_goods_attr[$attr['goods_attre_id']]['inventory'] < $attr['inventory']){
                    $errors .= '拼团价为'.$attr['collage_price'] .'的商品库存小于活动库存!';
                    continue;
                }else{
                    $arr['id'] = $attr['goods_attre_id'];
                    $arr['inventory'] = $new_goods_attr[$attr['goods_attre_id']]['inventory'] - $attr['inventory'];
                    array_push($modify_inventory,$arr);
                }
            }
        }
        if(!empty($errors)){
            return $this->renderJson([],$errors,ConstantService::$response_fail);
        }
        return $modify_inventory;
    }

    /**
     * 修改库存
     * @param $data
     * @return bool
     */
    private function _modifyInventory($data){

        if(empty($data)){
            return false;  
        }
        $redis = RedisServer::initialization();
        foreach ($data as $val){
            $goods = GoodsAttr::findOne(['id'=>$val['id']]);
            $goods->inventory = $val['inventory'];
            $goods->save();
            $key = ConstantService::$redis_key.$val['id'];

            if($redis->getRedis($key)) {
                $redis->addRedis($key, $val['inventory']);
            }
        }
        return true;
    }


}